// Wrap in IIFE to avoid polluting global scope
(function() {
    console.log("Gemini Downloader Content Script EXECUTING."); // Top-level log
    console.log("Gemini Downloader Content Script Loaded.");

    // --- Constants ---
    // Selectors based on analysis in docs/1.md and docs/3.md
    const RESPONSE_CONTAINER_SELECTOR = 'model-response';
    const MESSAGE_CONTENT_SELECTOR = 'message-content.model-response-text';
    const CONTENT_PANEL_SELECTOR = 'div.markdown.markdown-main-panel';
    // CSS Classes for our elements
    const BUTTON_CONTAINER_CLASS = 'gemini-download-controls';
    const BUTTON_HTML_CLASS = 'gemini-download-html-button';
    const BUTTON_MD_CLASS = 'gemini-download-md-button';
    // Marker class for idempotency check
    const INJECTION_MARKER_CLASS = BUTTON_CONTAINER_CLASS + '-injected';

    // --- Turndown Initialization ---
    let turndownService;
    try {
        if (typeof TurndownService !== 'undefined') {
            turndownService = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
            console.log("Turndown service initialized successfully.");
        } else {
            console.error("TurndownService is not defined. Make sure lib/turndown.js is loaded correctly before content.js.");
            turndownService = null;
        }
    } catch (e) {
        console.error("Error initializing Turndown:", e);
        turndownService = null; // Disable Markdown functionality
    }

    // --- Core Logic ---

    /**
     * Adds download buttons to a specific model response element if they don't exist.
     * @param {Element} responseElement The <model-response> element.
     */
    function addDownloadButtons(responseElement) {
        if (!responseElement || !responseElement.querySelector) {
            return;
        }

        const messageContent = responseElement.querySelector(MESSAGE_CONTENT_SELECTOR);
        if (!messageContent) {
            return; // Can't place buttons if anchor is missing
        }

        // Idempotency Check: Crucial for manual trigger to avoid duplicates
        if (messageContent.nextElementSibling?.classList.contains(INJECTION_MARKER_CLASS)) {
            return; // Buttons already exist
        }

        // Create container for our buttons
        const buttonContainer = document.createElement('div');
        buttonContainer.className = `${INJECTION_MARKER_CLASS} ${BUTTON_CONTAINER_CLASS}`; // Add marker class

        // Create HTML Download Button
        const btnHTML = document.createElement('button');
        btnHTML.textContent = '⬇️ HTML';
        btnHTML.className = BUTTON_HTML_CLASS;
        btnHTML.title = 'Download response as HTML';
        btnHTML.type = 'button';
        btnHTML.addEventListener('click', handleDownloadHTMLClick);
        buttonContainer.appendChild(btnHTML);

        // Create Markdown Download Button (only if Turndown loaded)
        if (turndownService) {
            const btnMD = document.createElement('button');
            btnMD.textContent = '⬇️ MD';
            btnMD.className = BUTTON_MD_CLASS;
            btnMD.title = 'Download response as Markdown';
            btnMD.type = 'button';
            btnMD.addEventListener('click', handleDownloadMDClick);
            buttonContainer.appendChild(btnMD);
        }

        // Inject the container immediately after the message content element
        messageContent.insertAdjacentElement('afterend', buttonContainer);
    }

    /**
     * Event handler for the HTML download button click.
     * @param {MouseEvent} event The click event.
     */
    function handleDownloadHTMLClick(event) {
        const button = event.currentTarget;
        const responseElement = button.closest(RESPONSE_CONTAINER_SELECTOR);
        if (!responseElement) {
             console.error("Could not find parent response container for HTML download.");
             alert("Error: Could not find the response container to download from.");
             return;
        }
        const contentPanel = responseElement.querySelector(CONTENT_PANEL_SELECTOR);

        if (!contentPanel) {
            console.error("Could not find content panel within response for HTML download:", responseElement);
            alert("Error: Could not find content panel to download.");
            return;
        }
        const htmlContent = contentPanel.innerHTML;
        const messageId = responseElement.closest('[data-message-id]')?.dataset.messageId;
        const filename = `gemini_response_${messageId || Date.now()}.html`;
        triggerDownload(htmlContent, filename, 'text/html;charset=utf-8');
    }

    /**
     * Event handler for the Markdown download button click.
     * @param {MouseEvent} event The click event.
     */
    function handleDownloadMDClick(event) {
         if (!turndownService) {
            console.error("Markdown download clicked, but Turndown service is not available.");
            alert("Error: Markdown conversion library (Turndown) not available.");
            return;
         }
        const button = event.currentTarget;
        const responseElement = button.closest(RESPONSE_CONTAINER_SELECTOR);
         if (!responseElement) {
             console.error("Could not find parent response container for Markdown download.");
             alert("Error: Could not find the response container to download from.");
             return;
         }
        const contentPanel = responseElement.querySelector(CONTENT_PANEL_SELECTOR);

        if (!contentPanel) {
            console.error("Could not find content panel within response for Markdown download:", responseElement);
            alert("Error: Could not find content panel to download.");
            return;
        }
        const htmlContent = contentPanel.innerHTML;
        let markdownContent = '';
         try {
             markdownContent = turndownService.turndown(htmlContent);
         } catch (e) {
              console.error("Turndown conversion failed:", e);
              alert("Error converting HTML to Markdown. See console for details.");
              return;
         }
        const messageId = responseElement.closest('[data-message-id]')?.dataset.messageId;
        const filename = `gemini_response_${messageId || Date.now()}.md`;
        triggerDownload(markdownContent, filename, 'text/markdown;charset=utf-8');
    }

    /**
     * Helper function to trigger file download using Blob and Object URL.
     * @param {string} content The file content.
     * @param {string} filename The desired filename.
     * @param {string} contentType The MIME type.
     */
    function triggerDownload(content, filename, contentType) {
        try {
            const blob = new Blob([content], { type: contentType });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = filename;
            document.body.appendChild(a); // Required for Firefox
            a.click();
            document.body.removeChild(a); // Clean up
            URL.revokeObjectURL(url); // Clean up
            console.log(`Download triggered for ${filename}`);
        } catch (e) {
            console.error("Error triggering download:", e);
            alert("Error creating download link. See console for details.");
        }
    }

    /**
     * Scans the current DOM for model responses and adds download buttons.
     */
    function scanAndAddButtons() {
        console.log("Scanning for Gemini responses to add buttons...");
        const responses = document.querySelectorAll(RESPONSE_CONTAINER_SELECTOR);
        console.log(`Found ${responses.length} potential response containers.`);
        if (responses.length > 0) {
            responses.forEach(addDownloadButtons);
            console.log("Finished processing responses.");
        } else {
            console.log("No response containers found in the current view.");
        }
    }

    // --- Message Listener ---
    // Listen for messages from the background script (triggered by browser action)
    console.log("Setting up message listener...");
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
        console.log("Message received in content script:", message, "From:", sender); // Log received message
        if (message.action === "scanGeminiResponses") {
            console.log("Action 'scanGeminiResponses' matched. Calling scanAndAddButtons...");
            scanAndAddButtons();
            // Optional: Send a response back to the background script
            sendResponse({ status: "scan complete", found: document.querySelectorAll(RESPONSE_CONTAINER_SELECTOR).length }); // Send back status
            return true; // Indicates you might send a response asynchronously
        }
    });

    // No automatic initialization needed anymore, logic runs on message receipt.
    console.log("Gemini Downloader content script ready to receive scan requests.");

})(); // End of IIFE